var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require("express-session");
var logger = require('morgan');
var ejs = require('ejs');
var wechat = require('./util/wechat');

const Secret = require('./config/index'),
  indexRouter = require('./routes/index'),
  schoolsRouter = require('./routes/schools'),
  systemRouter = require('./routes/system'),
  uploadRouter = require('./routes/upload'),
  miniRouter = require('./routes/mini-pro'),
  staffRouter = require('./routes/staff'),
  paymentRouter = require('./routes/payment'),
  leaveRouter = require('./routes/leave-info'),
  newsRouter = require('./routes/news'),
  clubRouter = require('./routes/club');
var app = express();
wechat.getAccessToken().then(token => {
  global.accessToken = token
})

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', ejs.__express);
app.set('view engine', 'html');



app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(session({
  secret: Secret.sessionSecret, //服务器端生成 session 的签名
  // name: "token", //修改session对应cookie的名称
  resave: false, //强制保存 session 即使它并没有变化
  saveUninitialized: true, //强制将未初始化的 session 存储
  rolling: true //在每次请求时强行设置 cookie，这将重置 cookie 过期时间（默认：false）
}))
app.use(express.static(path.join(__dirname, 'public')));
// //校验请求
// app.use(wechat.init);

app.use('/', indexRouter);
app.use('/upload', uploadRouter);
app.use('/mini', miniRouter);
app.use((req,res,next)=>{
  if (!req.session.isLogin){
    return res.redirect("/login.html");
  }
  next();
})
app.use('/schools', schoolsRouter);
app.use('/system', systemRouter);
app.use('/staff', staffRouter);
app.use('/payment', paymentRouter);
app.use('/leave-info', leaveRouter);
app.use('/news', newsRouter);
app.use('/club', clubRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;